<?php defined('SYSPATH') or die('No direct script access.');

require_once Kohana::find_file('classes', 'util');

// URL: /<context>/index.php/Home/
class Controller_Resource extends Controller_Base 
{
	const MODULE_NAME = 'Resource';
	
	private $resourceService;
	private $categoryService;
	
	public function __construct(Request $request, Response $response)
	{
		parent::__construct($request, $response);
		
		$this->resourceService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_RESOURCE.'/', ACCESS_TOKEN);
		$this->resourceService->init($this->_requestContext);

		$this->categoryService = new Service_GenericSeedniaServiceStub(WSROOT.WSCONTEXT.'/'.SERVICE_CATEGORY.'/', ACCESS_TOKEN);
		$this->categoryService->init($this->_requestContext);
	}
	
	private function loadDefaultContent(&$template)
	{
		$projectSid = $this->request->query('projectSid', NULL);
		if ($projectSid != NULL) {
			$project = $this->_projectHelper->loadProject($this->template);
			$this->template->set_global("enableProjectNavBar", true);
		}
	}
	
	public function after()
	{
		parent::after();
		$this->loadDefaultContent($this->template);
	}
	
	public function action_index()
	{
		$contentFrame = $this->index('Seednia::'.self::MODULE_NAME, NULL, 'default_sbar_left');
		$content = $this->createView('resource_content');
		$contentFrame->content = $content;

		try {
			$this->loadDefaultContent($this->template);

			$cateCriteria = array('kind' => 'Resource');
			$ref_categories = $this->categoryService->getList($cateCriteria, 0, 10);
			$content->ref_categories = Util_Data::toMapptingArray($ref_categories, 'sid', 'name');

			$projectSid = $this->request->query('projectSid', NULL);
			if ($projectSid != NULL) {
				$criteria['projectSid'] = $projectSid;
			}

			// Default form values
			$resource = array('domainId' => $this->_requestContext->domainId);
			$resource['projectSid'] = $projectSid;
			$content->resource = $resource;
					
			// TODO: set privacyLevel
			$content->resources = $this->resourceService->getList($criteria, 0, 20);

		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Add action_index: ' . $ex->getMessage());
		}

	}

	public function action_form()
	{
		if ($this->request->method() == "GET") {
			$this->showForm(NULL);
		} else if ($this->request->method() == "POST") {
			$this->doProcessForm();
		}
	}
	
	private function showForm($record)
	{
		$title = "Seednia::New ".self::MODULE_NAME;
		$resourceXid = $this->getXid();
		$isNew = ($resourceXid == 'new');

		if ($isNew && $record != NULL) {
			$resource = new ArrayObject;
			$resource->domainId = $this->_requestContext->domainId;
		} else {
			$project = $this->loadDefaultContent($this->template);
			$title = "Seednia::".self::MODULE_NAME.' '.$project->name;
		}
		$contentFrame = $this->loadViews($title, '_default_', 'default_sbar_right', 'default_sbar_left');		
		$content = $this->createView('resource_form');
		$contentFrame->content = $content;
		
		$content->project = $project;
		
		$cateCriteria = array('kind' => 'Resource');
		$ref_categories = $this->categoryService->getList($cateCriteria, 0, 10);
		$content->ref_categories = Util_Data::toMapptingArray($ref_categories, 'sid', 'name');
		
	}
	
	private function doProcessForm()
	{
		$resourceXid = $this->getXid();
		$isNew = ($resourceXid == 'new');
		try {
			$resource = array();
			$error = $this->_resourceHelper->saveFileResource($resource, $this->_requestContext, 'file', 'resource');
			$this->loadFormParams($resource);

			if ($error > 0) {
				$this->showForm($record);
			}
			
			$resource['creatorSid'] = $this->_sessionInfo->userInfo['userSid'];
			
			if ($isNew) {
				$sid = $this->resourceService->add($resource);

				if ($sid != null) {
					; // TODO: handle error
				}
			} else {
				$this->resourceService->update($record);
			}

			$redirTo = $this->request->post('return_url');
			if ($redirTo == NULL) {
				$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Resource';
				if (isset($resource['projectSid']))
					$redirTo = $redirTo."?projectSid=".$resource['projectSid'];
			}
			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	
	public function action_updateimage()
	{
		if (!$this->isMethodPost())
			return;
			
		try {
			$redirTo = controller_base_path($this->_requestContext, CONTROLLERPAGE).'/Domain';
			
			$resourceHelper = new Util_ResourceHelper($this->request, $this->_requestContext);
			$mediaRecord = $resourceHelper->saveFileResource($this->_requestContext, 'profileImage');
			$this->resourceService->update($mediaRecord, $this->_requestContext->domain->sid.'/image/profile');

			$this->request->redirect($redirTo);
		} catch (Exception $ex)
		{
			Kohana_Log::instance()->add(Kohana_Log::ERROR, 'Exception::Login | Message: ' . $ex->getMessage());
		}
	}
	
	private function loadFormParams(&$record)
	{
		$projectSid = $this->request->post('projectSid');
		if ($projectSid != NULL)
			$record['projectSid'] = $projectSid;
		$record['title'] = $this->request->post('title');
		$record['description'] = $this->request->post('description');
		
		$privacyLevel = $this->request->post('privacyLevel');
		if ($privacyLevel != NULL)
			$record['privacyLevel'] = $privacyLevel;

		$record['privacyLevel'] = Util_Data::getValue($this->request->post('privacyLevel'), 0);
		$record['tagNamesCsv'] = $this->request->post('tagNamesCsv');

		return $record;
	}
	

} // End Controller_Home